package com.example.springbootquartz;

import com.example.springbootquartz.job.MyJob;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;

import javax.sql.DataSource;

@SpringBootApplication
public class SpringBootQuartzApplication implements CommandLineRunner {


    public static void main(String[] args) {
        SpringApplication.run(SpringBootQuartzApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("加载完成!");
    }

    @Bean(name = "jobFactory")
    public MyAdaptableJobFactory myAdaptableJobFactory(){
        return new MyAdaptableJobFactory();
    }

    @Bean(name = "jobDetail")
    public JobDetailFactoryBean jobDetailFactoryBean() {// ScheduleTask为需要执行的任务
        JobDetailFactoryBean jobDetail = new JobDetailFactoryBean();
        jobDetail.setName("job1");// 设置任务的名字
        jobDetail.setGroup("myJobGroup1");// 设置任务的分组，这些属性都可以存储在数据库中，在多任务的时候使用
        jobDetail.setJobClass(MyJob.class);
        return jobDetail;
    }

    @Bean(name = "simpleJobTrigger")
    public SimpleTriggerFactoryBean simpleJobTrigger(JobDetailFactoryBean jobDetail) {
        SimpleTriggerFactoryBean trigger = new SimpleTriggerFactoryBean();
        trigger.setJobDetail(jobDetail.getObject());
        trigger.setStartDelay(5000L);
        trigger.setRepeatInterval(1000L); //每秒执行一次的simple定时任务
        trigger.setName("trigger");
        return trigger;
    }

    @Bean(name = "cronJobTrigger")
    public CronTriggerFactoryBean cronTriggerFactoryBean(JobDetailFactoryBean jobDetail){
        CronTriggerFactoryBean trigger = new CronTriggerFactoryBean();
        trigger.setJobDetail(jobDetail.getObject());
        trigger.setStartDelay(5000L);
        trigger.setCronExpression("0 0/1 * 1/1 * ? *"); //每分钟执行一次的cron定时任务
        trigger.setName("cron-trigger");// trigger的name
        return trigger;
    }

    @Autowired
    DataSource dataSource;

    @Bean(name = "scheduler")
    public SchedulerFactoryBean schedulerFactory(Trigger... triggers) {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        // 用于quartz集群,QuartzScheduler 启动时更新己存在的Job
        bean.setOverwriteExistingJobs(false);
        // 延时启动，应用启动1秒后
        bean.setStartupDelay(1);
        // 注册触发器,
        bean.setTriggers(triggers);
        bean.setDataSource(dataSource);
        bean.setJobFactory(myAdaptableJobFactory());
        return bean;
    }
}
